package com.fastwire.carriere.hibernate.daoimpl;

import org.hibernate.Criteria;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.fastwire.carriere.common.constant.UserConstants;
import com.fastwire.carriere.dao.DAOException;
import com.fastwire.carriere.dao.UserSessionDao;
import com.fastwire.carriere.user.entity.UserSession;

public class UserSessionDaoImpl extends AbstractDAOImpl implements
		UserSessionDao {

	@Override
	public UserSession getUserSession(String userName, long sessionId)
			throws DAOException {

		DetachedCriteria criteria = DetachedCriteria
				.forClass(UserSession.class);
		criteria.add(Restrictions.eq("userName", userName));
		criteria.add(Restrictions.eq("oid", sessionId));
		return (UserSession) getHibernateTemplate().findSingleObjByCriteria(
				criteria, false, false);

	}

	@Override
	public void invalidateUserSessions() throws DAOException {

		DetachedCriteria criteria = DetachedCriteria
				.forClass(UserSession.class);
		criteria.add(Restrictions.eq("status", UserConstants.STATUS_ACTIVE));

		Session session = HibernateUtil.openSession();
		try {
			session.beginTransaction();
			Criteria executableCriteria = criteria
					.getExecutableCriteria(session);
			executableCriteria.setFetchSize(1000);

			ScrollableResults scrollableResults = executableCriteria
					.scroll(ScrollMode.FORWARD_ONLY);
			int count = 0;
			while (scrollableResults.next()) {
				System.out.println("count is:" + count);
				Object object = scrollableResults.get(0);

				if (object instanceof UserSession) {
					((UserSession) object)
							.setStatus(UserConstants.STATUS_INACTIVE);
				}

				if (++count % 20 == 0) {
					session.flush();
					session.clear();
				}

			}

			session.flush();
			session.clear();
			session.getTransaction().commit();

		} catch (Exception ex) {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
			throw new DAOException(ex);
		} finally {
			HibernateUtil.close(session);

		}

	}
}
